var layer;
var element;
var form;
var laydate;
var table;
var upload;
layui.use(['element','layer','laydate','form','table','upload'], function(){
    layer = layui.layer;
    element = layui.element;
    form = layui.form;
    laydate = layui.laydate;
    table = layui.table;
    upload = layui.upload;
    $.ajax({
        type:"get",
        url:"/personnel/selDeptName",
        async:true,
        data:{},
        success:function(res){
            ztree(res.obj);
        }
    });
    laydate.render({
        elem: '#registerTime', //指定元素
        type: 'date',
        trigger: 'click' //时间时间为点击事件
    });
    load();
    selIndexUserTab('');
})
function ztree(data){
    var settingss = {
        data: {
            simpleData: {
                enable: true,  //true  false 分别表示 使用  不使用 简单数据模式
                idKey: "id",   //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据即 pIdKey 指定的属性值
            },
            key: {
                name: "menuName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check:{
            nocheckInherit:true   //当父节点设置 nocheck = true 时设置子节点是否自动继承 nocheck = true
        },
        callback:{
            onClick:chooseDept,
        }
    };
    zTreeObj = $.fn.zTree.init($("#treeDemo"), settingss, data); //初始化树
    zTreeObj.expandAll(true);   //true 节点全部展开、false节点收缩
}
/**
 *  获取对应部门下的后台管理人员
 * */
function chooseDept(event,treeId,treeNode){
    if(treeNode.tId=="treeDemo_1"){
        selIndexUserTab();
    }else{
        var deptId = treeNode.id;
        var obj = '';
        obj+="&deptId="+deptId;
        selIndexUserTab(obj);
    }
}
/**
 *  按钮  点击事件 刷新页面  返回  检索
 * */
function load(){
    //刷新页面按钮
    $(".tit_btn").bind('click',function(){
        location.reload();
    })
    //返回按钮
    $(".tit_btn2").bind('click',function(){
        window.history.go(-1);  //返回上一页
    })
    //检索按钮
    $("#indexBtn").bind('click',function(){
        selIndexUserTab('')
        layer.msg("搜索成功", {icon: 1});
    })
    //高级检索
    $("#index_btn1").bind('click',function(){
        AdvancedRetrieval();
    })
    //批量导入管理人员
    $("#importBtn").bind('click',function(){
        $("#imgbut").click();
    })        //图片上传
    var uploadInst = upload.render({
        elem: '#imgbut',
        url: '/personnel/importExcelUser',//改成您自己的上传接口,
        accept: 'file',
        acceptMime: 'application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        exts: 'xlsx|xls', //只允许上传excel文件
        size: 5000, //限制文件大小单位 KB
        done: function (res) {
            layer.msg('上传成功', {icon: 1});
            selIndexUserTab("");
            //上传成功的一些操作
        }, error: function () {
            //失败
            layer.msg('上传失败', {icon: 2});
        }
    });
    //添加管理人员 addBtn
    $("#addBtn").bind('click',function(){
        addBackUserInfo();
    })
}
/**
 * 添加后台管理人员
 * */
function addBackUserInfo() {
    layer.open({
        type:2,//弹出层的类型
        title:"添加管理人员",
        area:['1100px','590px'],//弹出层大小
        shade:0,//设置遮罩
        offset:'auto',//设置遮罩的位置
        resize:false,
        //弹出层内容
        content :"/personnel/layer/PerBackstageUser_layer_add.html",
        btn:['添加','取消'],
        yes:function(index,layero){
            var body = layero.find('iframe').contents();
            var form = '';
            var account = body.find("input[name=account]").val();
            var trueName = body.find("input[name=trueName]").val();
            var sex = body.find("select[name=sex]").val();
            var phoneNumber = body.find("input[name=phoneNumber]").val();
            var idCard = body.find("input[name=idCard]").val();
            var birthDate = body.find("input[name=birthDate]").val();
            var deptId = body.find("input[name=deptId]").val();
            var email = body.find("input[name=email]").val();
            var freestyle = body.find("textarea[name=freestyle]").val();
            var avatarUrl = body.find("input[name=avatarUrl]").val();
            if(!account){
                layer.msg("账号不能为空");
            }else{
                form+="&account="+account;
                if(!trueName){
                    layer.msg("账户昵称不能为空");
                }else{
                    form+="&trueName="+trueName;
                    if(!sex){
                        layer.msg("请选择性别");
                    }else{
                        form+="&sex="+sex;
                        if(!phoneNumber){
                            layer.msg("手机号不能为空");
                        }else{
                            form+="&phoneNumber="+phoneNumber
                            if(!idCard){
                                layer.msg("身份信息不能为空");
                            }else{
                                form+="&idCard="+idCard;
                                if(!birthDate){
                                    layer.msg("出生日期信息不能为空");
                                }else{
                                    form+="&birthDate="+birthDate;
                                    if(!deptId){
                                        layer.msg("请选择部门信息");
                                    }else{
                                        form+="&deptId="+deptId;
                                        if(!email){
                                            layer.msg("邮箱不能为空");
                                        }else{
                                            form+="&email="+email;
                                            if(!freestyle){
                                                form+="&freestyle="+''
                                            }else{
                                                form+="&freestyle="+freestyle
                                            }
                                            console.log(form)
                                            if(!avatarUrl){
                                                layer.msg("请为用户添加图片");
                                            }else{
                                                layer.confirm("您确定要添加`"+account+"`账户吗?",{
                                                    cancel:function(index, layero){
                                                        layer.msg("添加取消",{icon:2});
                                                    }
                                                }, function () {
                                                    $.post("/personnel/addBackUserInfo", form, function (res) {
                                                        if(res.obj){
                                                            layer.msg("添加成功",{icon:1});
                                                            selIndexUserTab();
                                                        }else{
                                                            layer.msg("添加失败",{icon:2});
                                                            selIndexUserTab();
                                                        }
                                                    });
                                                },function () {
                                                    layer.msg("停用取消",{icon:2});
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //selIndexUserTab(form);
            //layer.close(layer.index);
        },btn2:function(index,layero){

        }
    })
}

/**
 * 高级检索
 */
function AdvancedRetrieval(){
    layer.open({
        type:2,//弹出层的类型
        title:"高级检索",
        area:['520px','360px'],//弹出层大小
        shade:0,//设置遮罩
        offset:'auto',//设置遮罩的位置
        maxmin:true,
        //弹出层内容
        content :"/personnel/layer/PerBackstageUser_layer_index.html",
        btn:['确定','取消'],
        yes:function(index,layero){
            var body = layero.find('iframe').contents();
            var form = '';
            var email = body.find("input[name=email]").val();
            var phoneNumber = body.find("input[name=phoneNumber]").val();
            var idCard = body.find("input[name=idCard]").val();
            var status = body.find("select[name=status]").val();
            var sex = body.find("select[name=sex]").val();
            var enabled = body.find("select[name=enabled]").val();
            if(!email){
                form+="&email="+''
            }else{
                form+="&email="+email
            }
            if(!phoneNumber){
                form+="&phoneNumber="+0
            }else{
                form+="&phoneNumber="+phoneNumber
            }
            if(!idCard){
                form+="&idCard="+''
            }else{
                form+="&idCard="+idCard
            }
            if(!status){
                form+="&status="+0
            }else{
                form+="&status="+status
            }
            if(!sex){
                form+="&sex="+''
            }else{
                form+="&sex="+sex
            }
            if(!enabled){
                form+="&enabled="+0
            }else{
                form+="&enabled="+enabled
            }
            selIndexUserTab(form);
            layer.close(layer.index);
        },btn2:function(index,layero){

        }
    })
}
/**
 *  后台管理人员数据列表
 */
function selIndexUserTab(obj){
    var account = $("input[name=account]").val();
    var trueName = $("input[name=trueName]").val();
    var registerTime = $("input[name=registerTime]").val();
    var deptName = $("input[name=deptName]").val();
    if(!account){
        obj+="&account="+'';
    }else{
        obj+="&account="+account;
    }
    if(!trueName){
        obj+="&trueName="+'';
    }else{
        obj+="&trueName="+trueName;
    }
    if(!registerTime){
        obj+="&registerTime="+'';
    }else{
        obj+="&registerTime="+registerTime;
    }
    if(!deptName){
        obj+="&deptName="+'';
    }else{
        obj+="&deptName="+deptName;
    }
    $.ajax({
        url:"/personnel/selBackUserList",
        type:"post",
        dataType:"json",
        data:obj,
        success:function(item) {
            userTab(item.obj);
        }
    })
}
function userTab(item){
    table.render({
        elem:"#userListTab",//容器
        title:"后台管理人员数据列表",
        limit:6,//分页显示条数
        width:1124,
        data:item,
        toolbar:true,
        page:true,
        cols:[[//定义列
            {type:'checkbox',align:'center',width:40},//复选框靠左
            {title:'序号',align:'center',width:60,templet:function(data){
                    return data.LAY_INDEX;
                }},
            {field:"trueName",title:"用户姓名",align:'center',width:120},
            {field:"avatarUrl",title:"用户头像",align:'center',width:90,templet:function(data){
                    return "<img src=\""+data.avatarUrl+"\" style='width:60px;height:60px;'/>";
                }},
            {field:"sex",title:"性别",align:'center',width:80},
            {field:"account",title:"用户账号",align:'center',width:110},
            {field:"deptName",title:"所属部门",align:'center',width:100},
            {field:"enabled",title:"是否启用",align:'center',width:110,templet:function(data){
                    if(data.enabled==1){
                        return"<a style='display:inline-block;' onclick='updBackUserEnabled(\""+data.userId+"\",\""+data.enabled+"\",\""+data.trueName+"\",\""+data.status+"\")'><input type=\"checkbox\" checked lay-skin=\"switch\"  lay-filter='filter' lay-text='启用|停用'>"
                    }else if(data.enabled==2){
                        return"<a style='display:inline-block;' onclick='updBackUserEnabled(\""+data.userId+"\",\""+data.enabled+"\",\""+data.trueName+"\",\""+data.status+"\")')'><input type=\"checkbox\" lay-skin=\"switch\"  lay-filter='filter' lay-text='启用|停用'>"
                    }
            }},
            {field:"status",title:"账号状态",align:'center',width:112,templet:function(data){
                    if(data.status==1){
                        return"<a style='display:inline-block;' ><input type=\"checkbox\" disabled checked lay-skin=\"switch\"  lay-filter='filter' lay-text='使用中|已冻结'>"
                    }else if(data.status==2){
                        return"<a style='display:inline-block;'><input type=\"checkbox\" disabled lay-skin=\"switch\"  lay-filter='filter' lay-text='使用中|已注销'>"
                    }else if(data.status==3){
                        return"<a style='display:inline-block;'><input type=\"checkbox\" disabled  lay-skin=\"switch\"  lay-filter='filter' lay-text='使用中|已冻结'>"
                    }
            }},
            {field:"registerTime",title:"注册时间",align:'center',width:160},
            {field:"",title:"操作",align:'center',width:130,templet:function(data){
                    return "<a style='color:#009688;cursor:pointer;' onclick='selBackUser(\""+data.userId+"\")'>查看</a> "+
                            "<a style='color:#009688;cursor:pointer;' onclick='updBackUser(\""+data.userId+"\")'>编辑</a> "+
                            "<a style='color:#009688;cursor:pointer;' onclick='updBackUserStatus(\""+data.userId+"\",\""+data.enabled+"\",\""+data.status+"\",\""+data.account+"\")'>封停</a> ";
                }}
        ]]
    });
}
/**
 * 查看管理员信息
 * */
function selBackUser(userId){
    $.ajax({
        url:"/personnel/selBackUserList",
        type:"post",
        dataType:"json",
        data:{"userId":userId},
        success:function(item) {
            var data = item.obj[0];
            selBackUserInfo(data);
        }
    })
}
function selBackUserInfo(data){
    var tablename = "后台管理员数据列表";
    var type=5;
    var remark = data.userId+"";
    addOperLog(tablename,type,remark);
    layer.open({
        type:2,//弹出层的类型
        title:"查看用户信息",
        area:['1100px','650px'],//弹出层大小
        shade:0,//设置遮罩
        offset:'auto',//设置遮罩的位置
        resize:false,
        //弹出层内容
        content :"/personnel/layer/PerBackstageUser_layer_sel.html",
        btn:['关闭','取消'],
        yes:function(index,layero){
            layer.close(layer.index);
        },btn2:function(index,layero){

        },success:function(layero,index){
            var obj = layero.find('iframe').contents();
            obj.find("input[name=avatarUrl]").val(data.avatarUrl);
            obj.find(".account").html(data.account);
            obj.find(".trueName").html(data.trueName);
            obj.find("input[name=trueName]").val(data.trueName);
            obj.find("input[name=sex]").val(data.sex);
            obj.find("input[name=account]").val(data.account);
            obj.find("input[name=phoneNumber]").val(data.phoneNumber);
            obj.find("input[name=idCard]").val(data.idCard);
            obj.find("input[name=birthDate]").val(data.birthDate);
            obj.find("input[name=deptName]").val(data.deptName);
            obj.find("input[name=registerTime]").val(data.registerTime);
            obj.find("input[name=registerIp]").val(data.registerIp);
            obj.find("textarea[name=freestyle]").val(data.freestyle);
            obj.find("input[name=email]").val(data.email);
        }
    })
}
/**
 * 编辑信息
 * */
function updBackUser(userId){
    $.post("/personnel/selBackUserList", {"userId":userId}, function (res) {
        var data = res.obj[0];
        updBackUserInfo(data);
    })
}
function updBackUserInfo(data){
    layer.open({
        type:2,//弹出层的类型
        title:"编辑用户信息",
        area:['1100px','650px'],//弹出层大小
        shade:0,//设置遮罩
        resize:false,
        offset:'auto',//设置遮罩的位置
        //弹出层内容
        content :"/personnel/layer/PerBackstageUser_layer_upd.html",
        success:function(layero,index){
            var obj = layero.find('iframe').contents();
            obj.find("input[name=avatarUrl]").val(data.avatarUrl);
            obj.find("input[name=userId]").val(data.userId);
            obj.find(".account").html(data.account);
            obj.find(".trueName").html(data.trueName);
            obj.find("input[name=trueName]").val(data.trueName);
            obj.find("select[name=sex]").val(data.sex);
            obj.find("input[name=account]").val(data.account);
            obj.find("input[name=email]").val(data.email);
            obj.find("input[name=phoneNumber]").val(data.phoneNumber);
            obj.find("input[name=idCard]").val(data.idCard);
            obj.find("input[name=birthDate]").val(data.birthDate);
            obj.find("input[name=deptName]").val(data.deptName);
            obj.find("input[name=deptId]").val(data.deptId);
            obj.find("input[name=registerTime]").val(data.registerTime);
            obj.find("input[name=registerIp]").val(data.registerIp);
            obj.find("textarea[name=freestyle]").val(data.freestyle);
        }
    })
}
/**
 *  改变账号的状态
 * */
function updBackUserEnabled(userId,enabled,trueName,status){
    if(status==1){
        if(enabled==1){
            layer.confirm("您确定要停用`"+trueName+"`用户吗?",{
                cancel:function(index, layero){
                    layer.msg("停用取消",{icon:2});
                    selIndexUserTab();
                }
            }, function () {
                var enabled = 2;
                $.post("/personnel/updBackUserEnabled", {userId:userId,enabled:enabled}, function (res) {
                    if(res.obj){
                        layer.msg("停用成功",{icon:1});
                        selIndexUserTab();
                    }else{
                        layer.msg("停用失败",{icon:2});
                        selIndexUserTab();
                    }
                });
            },function () {
                layer.msg("停用取消",{icon:2});
                selIndexUserTab();
            });
        }else if(enabled==2){
            layer.confirm("您确定要启用`"+trueName+"`用户吗?",{
                cancel:function(index, layero){
                    layer.msg("启用取消",{icon:2});
                    selIndexUserTab();
                }
            }, function () {
                var enabled = 1;
                $.post("/personnel/updBackUserEnabled", {userId:userId,enabled:enabled}, function (res) {
                    if(res.obj){
                        layer.msg("启用成功",{icon:1});
                        selIndexUserTab();
                    }else{
                        layer.msg("启用失败",{icon:2});
                        selIndexUserTab();
                    }
                });
            },function () {
                layer.msg("启用取消",{icon:2});
                selIndexUserTab();
            });
        }
    }else{
        layer.msg("该账户已被冻结，无法启用",{icon:2});
        selIndexUserTab();
    }
}
/**
 * 封停账号
 * */
function updBackUserStatus(userId,enabled,status,account){
    if(status==3){
        layer.msg("该账号已冻结，请勿重复操作");
    }else if(status==2){
        layer.msg("该账号已冻结，请勿重复操作");
    }else if(status==1){
        if(enabled==1){
            var enable = 2;
            var sta = 3;
            layerOff(userId,account,enable,sta);
        }else if(enabled==2){
            var enable = 0;
            var sta = 3;
            layerOff(userId,account,enable,sta);
        }
    }
}
function layerOff(userId,account,enable,sta){
    layer.open({
        type:2,//弹出层的类型
        title:"封停后台用户",
        area:['550px','400px'],//弹出层大小
        shade:0,//设置遮罩
        offset:'auto',//设置遮罩的位置
        maxmin:true,
        //弹出层内容
        content :"/personnel/layer/PerUserList_layer_checkswitchoff.html",
        success:function(layero,index){
            //查找当前引入的iframe的内容
            var obj = layero.find('iframe').contents();
            obj.find("input[name=userId]").val(userId);
            obj.find("input[name=account]").val(account);
            var user=localStorage.getItem("user");
            user=JSON.parse(user);//将获取json字符串转json对象
            var implementId = user.userId;
            obj.find("input[name=implementId]").val(implementId);
        },
        btn:['确定','取消'],
        yes:function(index,layero){
            var body = layero.find('iframe').contents();
            var form = $(body).find('form').serialize();
            var type = 2;
            addClosureLog(userId,type);
            addClosure(form);
            updBackStatus(userId,enable,sta);
            layer.close(layer.index);
        },btn2:function(index,layero){

        }
    })
}
function updBackStatus(userId,enable,status){
    $.post("/personnel/updBackUserStatus", {userId:userId,enabled:enable,status:status}, function (res) {
        if(res.obj){
            selIndexUserTab();
        }else{
            selIndexUserTab();
        }
    })
}
function addClosure(vals){
    //更改用户状态 为3（停用）
    //添加停用日志  和添加停用的用户
    vals+="&type="+3;
    $.ajax({
        url:"/personnel/addClosure",
        type:"post",
        dataType:"json",
        data:vals,
        success:function(data){
            if(data){
                layer.msg("封停成功", {icon: 1});
                selIndexUserTab();
            }else{
                layer.msg("封停失败", {icon: 2});
                selIndexUserTab();
            }
        }
    })
}
/**
 *  添加后台操作日志
 * */
function addOperLog(tablename,type,remark){
    var create=localStorage.getItem("user");
    create=JSON.parse(create);//将获取json字符串转json对象
    var mid = create.userId;
    form+="&mid="+mid;
    form+="&tablename="+tablename;
    form+="&type="+type;
    form+="&remark="+remark;
    $.post("/personnel/addOperationLog", form, function (res) {
        form="";
    });
}
/**
 *  添加封停操作日志
 * */
function addClosureLog(userId,type){
    var create=localStorage.getItem("user");
    create=JSON.parse(create);//将获取json字符串转json对象
    var operationId = create.userId;
    form+="&operationId="+operationId;
    form+="&userId="+userId;
    form+="&type="+type;
    $.post("/personnel/addClosureLog", form, function (res) {
        form="";
    });
}
